package zunge.tool.db.sql;
import org.mybeans.dao.DAOException;
import org.mybeans.factory.BeanFactory;
import org.mybeans.factory.BeanFactoryException;
import org.mybeans.factory.BeanTable;
import org.mybeans.factory.RollbackException;
import org.mybeans.factory.Transaction;

public class BeanDAO<MyBean> {
	private BeanFactory<MyBean> factory;
	private BeanTable<MyBean> table;
	
	static String jdbcDriver = "com.mysql.jdbc.Driver";
	
	
	public BeanDAO(Class<MyBean> beanClass, String jdbcURL, 
			String userName, String password,
			String tableName, String mainColumn) throws DAOException {
		try{
	       	table = BeanTable.getSQLInstance(beanClass,tableName,jdbcDriver, jdbcURL, userName, password);
	        if (!table.exists()) table.create(mainColumn);
	        table.setIdleConnectionCleanup(true);
	        factory = table.getFactory();
		}catch (BeanFactoryException e) {throw new DAOException(e);}
	}
	
	public void create(MyBean bean) throws DAOException{
		try{
			
			Transaction.begin();
			MyBean beanDB = factory.create(factory.getPrimaryKeyValues(bean));
			factory.copyInto(bean, beanDB); //copyInfo does not copy the primary key
			Transaction.commit();
			
		}catch(RollbackException e){throw new DAOException(e);
		}finally{
			if(Transaction.isActive()){
				Transaction.rollback();
			}
		}
	}
	
}
